package com.lagou.rabbitmq.service;

import com.lagou.rabbitmq.entity.OrderInfo;
import com.lagou.rabbitmq.mapper.OrderInfoMapper;
import com.lagou.rabbitmq.mapper.PayInfoMapper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private PayInfoMapper payInfoMapper;

    public Long order(Long userId, Integer courseId) throws Exception {

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setCourseId(courseId);
        orderInfo.setCoursePrice(9800L);
        orderInfo.setOrderPrice(9800L - 5000L);
        orderInfo.setStatus(1);
        orderInfoMapper.add(orderInfo);

        System.out.println("生成订单：" + orderInfo.getOrderId());

        // 进入待支付订单的TTL队列
        rabbitTemplate.convertAndSend("exchange.order", "order", orderInfo.getOrderId());

        return orderInfo.getOrderId();
    }

    public OrderInfo getOrderInfoById(Long userId, Long orderId) throws Exception {
        OrderInfo orderInfo = orderInfoMapper.getOrderInfoById(userId, orderId);
        if (orderInfo == null) {
            throw new Exception("订单取得失败");
        }

        return orderInfo;
    }

    public Integer getOrderStatusById(Long userId, Long orderId) throws Exception {
        Integer orderStatus = orderInfoMapper.getOrderStatusById(userId, orderId);
        if (orderStatus == null) {
            throw new Exception("订单状态取得失败");
        }

        return orderStatus;
    }

    @RabbitListener(queues = "queue.order.dlx")
    public void invalidOrder(Long orderId) {
        orderInfoMapper.invalid(orderId);
        System.out.println("超时失效订单：" + orderId);
    }

    public void paidOrder(Long userId, Long orderId) {
        orderInfoMapper.paid(userId, orderId);
        System.out.println("支付订单：" + orderId);
    }
}
